package com.kgc.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kgc.annotation.CheckPermission;
import com.kgc.entity.BuyCart;
import com.kgc.entity.BuyCartProduct;
import com.kgc.entity.Order;
import com.kgc.entity.OrderDetail;
import com.kgc.service.AddressService;
import com.kgc.service.OrderService;
import com.kgc.util.ResultAjax;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author :qinya
 * @PackageName:com.kgc.controller
 * @ClassName: OrderController
 * @Description: TODO
 * @date : 2025/5/23,13:47
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @GetMapping("/page")
    @CheckPermission({"1", "0"})
    public ResultAjax queryByPage(@RequestParam Map<String, String> params) {
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isEmpty(params.get("searchUserName"))) {
            map.put("searchUserName", '%' + params.get("searchUserName") + '%');
        }
        if (!StringUtils.isEmpty(params.get("searchOrderNum"))) {
            map.put("searchOrderNum", params.get("searchOrderNum"));
        }
        if (!StringUtils.isEmpty(params.get("isPay"))) {
            map.put("isPay", Integer.parseInt(params.get("isPay")));
        }
        if (!StringUtils.isEmpty(params.get("startDate"))) {
            map.put("startDate", params.get("startDate"));
            logger.debug("起始日期" + map.get("startDate"));
        }
        if (!StringUtils.isEmpty(params.get("endDate"))) {
            map.put("endDate", params.get("endDate"));
            logger.debug("截止日期" + map.get("endDate"));
        }
        if (params.containsKey("userId")) {
            map.put("userId", Integer.parseInt(params.get("userId")));
        }
        map.put("isAll", Integer.parseInt(params.get("isAll")));
        map.put("pageNum", Integer.parseInt(params.get("pageNum")));
        map.put("pageSize", Integer.parseInt(params.get("pageSize")));
        return ResultAjax.success().add("pageInfo", orderService.selectByPage(map));
    }

    @GetMapping("/del/{id}")
    @CheckPermission({"1", "0"})
    public ResultAjax delOrder(@PathVariable("id") int id) {
        return ResultAjax.success().add("delStatus", orderService.delOrder(id));
    }

    /**
     * 添加订单
     *
     * @param order
     * @return
     */
    @PostMapping("/add")
    @CheckPermission({"1", "0"})
    public ResultAjax addOrder(@RequestBody Order order) throws JsonProcessingException {
        order.setCreateTime(new Date());
        order.setSerialNumber(UUID.randomUUID().toString().replace("-", ""));
        order.setUserAddress(addressService.selectById(order.getAddressId()).address);
        boolean temp = orderService.addOrder(order);
        boolean flag = false;
        if (temp) {
            ObjectMapper om = new ObjectMapper();
            BuyCart buyCart = om.readValue(stringRedisTemplate.opsForValue().get(order.getUserId() + "buyCart"), BuyCart.class);
            Iterator<BuyCartProduct> valueIterator = buyCart.getMap().values().iterator();
            while (valueIterator.hasNext()) {
                BuyCartProduct product = valueIterator.next();
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(order.getId());
                orderDetail.setProductId(Integer.parseInt(product.getProductId()));
                orderDetail.setQuantity(product.getCount());
                orderDetail.setCost(product.getCount() * Double.valueOf(product.getPrice()));
                flag = orderService.addOrderDetail(orderDetail);
            }
            if (flag) {
                //作预出库
                flag = orderService.changeStock(order.getId(), "-");
            }
        }
        if (flag) {
            //redis监听订单号
            stringRedisTemplate.opsForValue().set(order.getSerialNumber(), order.getSerialNumber(), 30, TimeUnit.SECONDS);
            //清空购物车
            stringRedisTemplate.delete(order.getUserId().toString() + "buyCart");
            return ResultAjax.success().add("serialNumber", order.getSerialNumber());
        }
        return ResultAjax.error().add("serialNumber", false);
    }
}
